package cn.kgc.springboot.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.kgc.springboot.common.CodeMsg;
import cn.kgc.springboot.dto.UserDTO;
import cn.kgc.springboot.entity.User;
import cn.kgc.springboot.service.UserService;
import cn.kgc.springboot.util.JWTUtil;
import cn.kgc.springboot.util.LayTable;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author: mosin
 * @version: v1.0  2022/8/1
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("getAll")
    public LayTable getAll(String loginName, Integer page, Integer limit) {

        return userService.getAll(loginName, page, limit);

    }


    @RequestMapping("delete")
    public LayTable deleteById(Integer[] ids) {

        return userService.deleteById(ids);

    }

    @RequestMapping("add")
    public LayTable addUser(UserDTO userDTO) {
        System.out.println("userDTO = " + userDTO);
        return userService.addUser(userDTO);

    }

    @RequestMapping("update")
    public LayTable updateUser(UserDTO userDTO) {
        System.out.println("userDTO = " + userDTO);
        return userService.updateUser(userDTO);

    }

    // 动态加载菜单
    @RequestMapping("loadMenu")
    public LayTable loadMenu(Integer userId) {
        return userService.loadMenu(userId);
    }


    @RequestMapping("captcha")
    public void loadMenu(HttpServletResponse response) {

        LineCaptcha lineCaptcha = new LineCaptcha(260, 110, 4, 3);
        String code = lineCaptcha.getCode();
        // TODO  将验证码 存入 redis缓存
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("login")
    public LayTable login(String username, String password) {

        User user = userService.getOne(new QueryWrapper<User>().eq("login_name", username).eq("password", password));

        if (ObjectUtils.isNull(user)) {
            return new LayTable().setCode(CodeMsg.ERROR.getCode()).setMsg(CodeMsg.ERROR.getMsg());
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("username", user.getLoginName());
        map.put("id", user.getIdCard());

        String token = JWTUtil.creatToken(map);
        user.setToken(token);

        return new LayTable().setCode(CodeMsg.SUCCESS.getCode()).setMsg(CodeMsg.SUCCESS.getMsg()).setData(user);

    }


}
